import {Component, OnInit, Input, OnChanges} from "@angular/core";
import {OneMapService} from "../one-map.service";
import {DatePipe} from "@angular/common";
import {NzMessageService} from "ng-zorro-antd";
import {forkJoin} from "rxjs";
import {DialogBase} from "../dialog-base";
import {FetchService} from "../../../core/net/fetch.service";

@Component({
    selector: "app-dialog-gate",
    templateUrl: "./dialog-gate.component.html",
    styleUrls: [
        "../dialog-dam/dialog-dam.component.scss",
        "./dialog-gate.component.scss"
    ]
})
export class DialogGateComponent extends DialogBase implements OnChanges {
    @Input() data: any;
    tabs: any[] = [
        "闸门状态",
        "过程线",
        "设备运行状态",
        "预警提醒",
        // "水位流量关系",
        // "旬月特征",
        // "历史同期",
        // "特征信息"
    ];
    activeIdx: number = 0;

    gateStatus: any = {};
    historyTypes: any[] = ["流量", "开度"];
    historyKeys: any[] = ["flux", "degree"];
    degreeList: any[] = [];
    strobeNumber: any;
    gateHeight: number = 3;
    equTableData = [];
    warningTableData = [];

    constructor(
        private mapService: OneMapService,
        public datePipe: DatePipe,
        private message: NzMessageService,
        private fetchService: FetchService
    ) {
        super(datePipe);
    }

    ngOnChanges() {
        const data = this.data;
        let code;
        if (data.buildCode) {
            code = data.buildCode;
        } else if (data.properties) {
            code = data.properties.code;
        }
        data.code = data.strobeCode || code || 'HN-5-QJ1';
        console.log(this.data);
        if (data.strobeNumber) {
            this.strobeNumber = Number(data.strobeNumber);
            this.degreeList = new Array(this.strobeNumber);
        } else {
            this.strobeNumber = '-';
        }
        if (String(data.size).indexOf('*') > -1) {
            if (data.size.split('*').length > 1) {
                this.gateHeight = parseFloat(data.size.split('*')[1]);
            } else if (data.size.split('×').length > 1) {
                this.gateHeight = parseFloat(data.size.split('×')[1]);
            }
        } else {
            this.gateHeight = 0;
        }
        setTimeout(() => {
            this.initData();
        }, 300);
    }

    initData() {
        switch (this.activeIdx) {
            case 0:
                this.onQueryStatus();
                break;
            case 1:
                this.onQueryProcessList();
                break;
            case 2:
                this.queryEquInfo();
                break;
            case 3:
                this.onQueryMonthList();
                break;
            case 4:
                this.onQueryHistory();
                break;
            case 5:
                break;
        }
    }

    onSelectChange(e) {
        this.activeIdx = e.index;
        this.initData();
    }

    getProcessListGate() {
        return this.mapService.getProcessListGate({
            stadiaCode: this.data.code,
            beginTime: this.datePipe.transform(this.beginDate, "yyyy-MM-dd"),
            endTime: this.datePipe.transform(this.endDate, "yyyy-MM-dd"),
            pageSize: this.pageSize
        });
    }

    getMonthListGate() {
        return this.mapService.getMonthListGate({
            stadiaCode: this.data.code,
            year: this.curYear,
            history: `${this.year1.getFullYear()},${this.year2.getFullYear()}`
        });
    }

    queryEquInfo(reset: boolean = false): void {
        const params = {
            pageNum: 1,
            pageSize: 10
        };
        this.fetchService.post('base/wrsBrwaterDam/queryDamInfoList', params).subscribe(res => {
            this.equTableData = res['list'].filter(item => item.stadiaCode == this.data.code);
        });
    }

    onQueryStatus() {
        this.getProcessListGate().subscribe(res => {
            if (res["list"].length) {
                this.gateStatus = res["list"][res["list"].length - 1];
                this.degreeList.map(d => {
                    d = this.gateStatus.degree;
                });
            }
        });
    }

    onQueryProcessList() {
        this.getProcessListGate().subscribe(res => {
            console.log(res);
            const list = res["list"];
            this.processOptChange = {
                legend: {
                    data: ["闸前水位", "闸后水位", "流量"],
                    bottom: 10
                },
                xAxis: [
                    {
                        data: this.getItemValues(list, "meaTime", true)
                    }
                ],
                series: [
                    {
                        name: "闸前水位",
                        data: this.getItemValues(list, "heightUp")
                    },
                    {
                        name: "闸后水位",
                        data: this.getItemValues(list, "heightDown")
                    },
                    {
                        data: this.getItemValues(list, "flux")
                    }
                ]
            };
            console.log(this.processOpt);
        });
    }

    onQueryMonthList() {
        this.getMonthListGate().subscribe((data: any) => {
            // console.log(data);
            this.monthData = data;
            this.changeMonthChart();
        });
    }

    onQueryHistory() {
        const history1 = this.mapService.getProcessListGate({
            ...this.getDateList(this.historyYear1),
            stadiaCode: this.data.code
        });
        const history2 = this.mapService.getProcessListGate({
            ...this.getDateList(this.historyYear2),
            stadiaCode: this.data.code
        });
        forkJoin(history1, history2).subscribe(datas => {
            this.historyLists = datas.map(data => {
                return data["list"];
            });
            this.changeHistoryChart();
        });
    }

    changeMonthChart() {
        console.log(this.selectedIdx);
        const data = this.monthData;
        const keys: any[] = Object.keys(data);
        this.monthOptChange = {
            legend: {
                data: keys.map(k => {
                    return k == "historyYear" ? "历史年段" : k;
                })
            },
            series: keys.map(key => {
                return {
                    name: key == "historyYear" ? "历史年段" : key,
                    type: "bar",
                    data: data[key].map(item => {
                        return item[this.eigenKeys[this.selectedIdx]];
                    })
                };
            })
        };
        // console.log(this.monthOptChange);
    }

    changeHistoryChart() {
        const lists = this.historyLists;
        if (!lists[0].length || !lists[1].length) {
            this.message.error("---无数据---");
            return;
        }
        const xAxisData = lists[0].map(item => {
            return item.meaTime.substr(5);
        });
        const legendData: any[] = [];
        const seriesData: any[] = [];
        lists.map(list => {
            const year = list[0].meaTime.substr(0, 4);
            legendData.push(year);
            seriesData.push({
                name: year,
                type: "line",
                data: list.map(item => {
                    return item[this.historyKeys[this.hType]];
                })
            });
        });
        this.historyOptChange = {
            legend: {
                data: legendData
            },
            xAxis: {
                data: xAxisData
            },
            series: seriesData
        };
        // console.log(this.historyOptChange);
    }
}
